<?php
namespace Api\Controller;
use Api\Model\WeixinUserModel;
use Common\Controller\BaseController;
use Common\Service\WeixinLiteService;
use Common\Util\CacheUtils;
use Common\Util\ConfigUtils;
use Common\Util\EncryUtils;
use Common\Util\WXBizDataCrypt;
use Think\Model;


/**
 * Created by PhpStorm.
 * User: XZR
 * Date: 2018/8/1
 * Time: 14:42
 */
class WechatController extends BaseController
{
    /**
     * 小程序登录
     */
    public function liteLogin(){
        $this->validateParam(array("code"));
        $code = $this->getPostParam("code", "");
        $rstdata = WeixinLiteService::obtainLoginInfo($code);
        if($rstdata['errcode']){
            $rst['result']=201;
            $rst['msg']="授权失败";
            $this->formatjson($rst);
        }
        $rst['result']=200;
        //$rst['info']=$rstdata;
        $rst['msg']="授权成功";
        $rst['token']=EncryUtils::encrypt($rstdata['openid']);
        WeixinUserModel::singleton()->addUser($rstdata['openid']);
        //缓存session_key(解密用)
        CacheUtils::set($rstdata['openid'],$rstdata['session_key'],3600*24*90);
        $this->formatjson($rst);
    }

    //获取用户信息
    public function getUserInfo(){
        $this->validateParam(array("iv","encryptedData","token"));
        $encryptedData  =  $this->getPostParam("encryptedData", "");
        $iv             =  $this->getPostParam("iv", "");
        $token =$this->getPostParam("token", "");
        $appid = ConfigUtils::getConfig("WEIXIN_LITE_APPID");
        $sessionKey = CacheUtils::get(EncryUtils::decrypt($token));
        $is_encode = $this->getPostParam("is_encode",0);
        $this->log();
        if($is_encode){
            $encryptedData = urldecode($encryptedData);
        }

        $pc = new WXBizDataCrypt($appid,$sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

/*        if($is_encode){
            print_r($errCode);
        }*/
        if ($errCode == 0) {
            //添加微信用户信息
            $user = json_decode($data,true);
            WeixinUserModel::singleton()->addOrUpdate(EncryUtils::decrypt($token),$user);
            $rst['result']=200;
            $rst['info']=$user;
            $rst['msg']="解密成功";
            file_put_contents('encrypt_success_data.txt', date('Y-m-d H:i:s') . PHP_EOL . $encryptedData . PHP_EOL . $iv . PHP_EOL . $token . PHP_EOL . $appid . PHP_EOL . $sessionKey . PHP_EOL, FILE_APPEND);
        } else {
            file_put_contents('encrypt_error_data.txt', date('Y-m-d H:i:s') . PHP_EOL . $encryptedData . PHP_EOL . $iv . PHP_EOL . $token . PHP_EOL . $appid . PHP_EOL . $sessionKey . PHP_EOL, FILE_APPEND);
            $rst['result']=201;
            $rst['info']=$errCode;
            $rst['msg']="解密出错";
        }
        $this->formatjson($rst);
    }

    private function log()
    {
        $body = json_decode(file_get_contents('php://input'));
        $request = [
            'param' => $_REQUEST,
        ];
        $body and $request['body'] = $body;
        (new Model())->table('__API_LOG__')->add([
            'action' => 'Wechat' . '@' . 'getUserInfo',
            'method' => $_SERVER['REQUEST_METHOD'],
            'request' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }
}
